import Router from 'koa-router'
import sha1 from 'sha1'
import { parse as urlParse } from 'url'
import { parse as queryParse } from 'querystring'
import config from '../config'
import reply from '../wechat/reply'
import wechatMiddle from '../wechat-lib/middleware'
import { getWechat, getOAuth } from '../wechat'
import { randomBytes } from 'crypto'
import qr from 'qr-image'
import fs from 'fs'


export const router = app => {

  const router = new Router()

  app.use(async (ctx, next) => {
    const start = Date.now();
    await next();
    const ms = Date.now() - start;
    ctx.set('X-Response-Time', `${ms}ms`);
  })

  // logger

  app.use(async (ctx, next) => {
    const start = Date.now();
    await next();
    const ms = Date.now() - start;
    console.log(`${ctx.method} ${ctx.url} - ${ms}`);
  })


  router.all('/wechat-hear', wechatMiddle(config.wechat, reply))

  router.get('/wechat-redirect', (ctx, next) => {
    const target = config.SITE_ROOT_URL + '/oauth'
    const scope = 'snsapi_userinfo'
    const { visit, id } = ctx.query
    const params = id ? `${visit}_${id}` : visit

    const oauth = getOAuth()

    const url = oauth.getAuthorizeURL(scope, target, params)
    console.log(url)
    ctx.redirect(url)
  })
  
  router.get('/wechat-oauth', async (ctx, next) => {
    let url = ctx.query.url
    url = decodeURIComponent(url)

    const urlObj = urlParse(url)
    const params = queryParse(urlObj.query)

    const code = params.code
    const oauth = getOAuth()
    const data = await oauth.fetchAccessToken(code)
    const user = await oauth.getUserInfo(data.access_token, data.unionid)
    console.log(user)
    ctx.body = {
      success: true,
      data: user
    }
  })

  router.get('/wechat-wxqrcode', async (ctx, next) => {
    const timer = Date.now()
    const randomstr = Math.random().toString(36).substr(2)
    const str = [timer, randomstr].sort().join('')
    const uuid = sha1(str)
    const code = qr.imageSync('http://test.wlijie.com/qrlogin/?uuid=' + uuid, { type: 'png' })
    const qrcode = 'data:image/jpg;base64,' + code.toString('base64')
    ctx.body = {
      success: true,
      data: {
        uuid: uuid,
        qrcode: qrcode
      }
    }
  })

  router.get('/wechat-login', async (ctx, next) => {
    console.log()

   
  })

  app
    .use(router.routes())
    .use(router.allowedMethods())
}
